package org.springblade.modules.admin.service.parts.impl.strategy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springblade.common.constant.MaintenanceSmsConstant;
import org.springblade.common.constant.TemplateMsgConstant;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.BusinessApprove;
import org.springblade.modules.admin.entity.MaintainMalfunctionLog;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.ApproveStatusEnum;
import org.springblade.modules.admin.enums.ApproveTypeEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.approve.strategy.ApproveBusinessFlow;
import org.springblade.modules.admin.service.approve.strategy.ApproveBusinessStrategy;
import org.springblade.modules.admin.service.parts.AbstractOrderStateStrategy;
import org.springblade.modules.admin.utils.AsyncUtils;
import org.springblade.modules.admin.vo.BusinessApproveVO;
import org.springblade.modules.admin.vo.parts.PartsExecuteVO;
import org.springblade.modules.resource.utils.SmsUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.vo.SimpleUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 待审批策略实现 -> 对应状态1，处理回退逻辑
 * @Author ysq
 * @Date 2024/05/16
 **/
@Slf4j
@Service("approveOrderStrategy")
public class ApproveOrderStrategyImpl extends AbstractOrderStateStrategy {

	@Autowired
	private AsyncUtils asyncUtils;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Object handle(PartsExecuteVO executeParams) {
		log.info("=============配件工单-状态流转-待审批(回退)，时间:[{}]，参数：[{}]============", DateUtil.now(), executeParams);
		BusinessApprove businessApprove = businessApproveService.getByWorkOrderId(executeParams.getPlanId());
		if (businessApprove == null) {
			log.error("审批流程不存在!, 工单id：[{}]", executeParams.getPlanId());
			return R.status(false);
		}
		if (businessApprove.getApproveStatus() != ApproveStatusEnum.PENDING.getId()) {
			log.error("当前流程状态为：{},不能进行回退, 工单id：[{}]",  ApproveStatusEnum.getName(businessApprove.getApproveStatus()), executeParams.getPlanId());
			return R.status(false);
		}
		// 更新审批 -> 回退
		BusinessApproveVO businessApproveVO = new BusinessApproveVO();
		businessApproveVO.setId(businessApprove.getId());
		businessApproveVO.setApproveStatus(ApproveStatusEnum.RETURN.getId());
		businessApproveVO.setRemark(executeParams.getRemark());
		ApproveBusinessFlow flowStrategy = ApproveBusinessStrategy.get(ApproveTypeEnum.ACCESSORY_APPLY.getId());
		boolean flowRes = flowStrategy.approve(businessApproveVO);
		if (!flowRes) {
			log.error("状态流转失败, 工单id：[{}]", executeParams.getPlanId());
			return R.status(false);
		}
		return R.data("重新提交");

		// 工单状态对应变更
//		if (executeParams.getApproveStatus() == ApproveStatusEnum.PASSED.getId()) {
//			// 审批通过, 状态流转 待审批 -> 待报价
//			executeParams.setEvent("PARTS_OFFER");
//			return orderStateMachineService.execute(Func.toMap(executeParams));
//		} else if (executeParams.getApproveStatus() == ApproveStatusEnum.REJECT.getId()){
//			// 审批拒绝, 状态流转 待审批 -> 已关闭
//			boolean planRes = maintainPlanContentService.update(Wrappers.<MaintainPlanContent>update().lambda()
//				.set(MaintainPlanContent::getStatus, TaskStatusEnum.PARTS_CLOSE.getStatus())
//				.eq(MaintainPlanContent::getId, executeParams.getPlanId()));
//			if (!planRes) {
//				throw new ServiceException("状态流转失败，工单id: " + executeParams.getPlanId());
//            }
//			return null;
//		} else {
//			// 审批回退, 工单状态不变
//			return null;
//		}
	}

	@Override
	public void after(PartsExecuteVO executeParams) {
		MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(executeParams.getPlanId());
		List<MaintainMalfunctionLog> maintainMalfunctionLogList = maintainMalfunctionLogService.list(Wrappers.<MaintainMalfunctionLog>lambdaQuery().eq(MaintainMalfunctionLog::getPlanId, executeParams.getPlanId()).orderByDesc(MaintainMalfunctionLog::getId));
		MaintainMalfunctionLog maintainMalfunctionLog = null;
		if (Func.isNotEmpty(maintainMalfunctionLogList)) {
			// 更新任务追踪日志
			maintainMalfunctionLog = maintainMalfunctionLogList.get(0);
			maintainMalfunctionLog.setExt(JSONObject.toJSONString(MapUtil.ofEntries(MapUtil.entry("approveDesc", ApproveStatusEnum.RETURN.getName()), MapUtil.entry("remark", executeParams.getRemark()))));
			maintainMalfunctionLogService.updateById(maintainMalfunctionLog);
		}

		User createUser = userService.getById(maintainPlanContent.getCreateUser());
		maintainMalfunctionLogService.insertWorkLog(executeParams.getPlanId(), "待处理", TaskStatusEnum.valueOf(executeParams.getEvent()).getStatus(), null, maintainPlanContent.getCreateUser(), createUser != null ? createUser.getRealName() : null);

		log.info("===========配件申请退回-发送手机短信,接收人:[{}], 手机号码:[{}]===========", createUser.getRealName(), createUser.getPhone());
		Map<String, String> smsParam = new HashMap<>(4);
		smsParam.put("status", "已退回");
		smsParam.put("page", "我的申请");
		smsParam.put("location", "待处理");
		SmsUtil.sendMessage(MaintenanceSmsConstant.ACCESSORIES_MESSAGE, BladeConstant.ADMIN_TENANT_ID, smsParam, createUser.getPhone());

		// 审批退回，发送公众号消息提醒
		SimpleUserVO applyUserInfo = userService.getSimpleUserInfo(maintainPlanContent.getCreateUser());
		if (Func.isNotEmpty(applyUserInfo.getOpenid())) {
			// 跳转链接
			String skipUrl = String.format("pages/approve/partApprovalDetail?id=%s&type=3", executeParams.getPlanId());
			Map<String, String> templateDataMap = new HashMap<>(8);
			templateDataMap.put("first", "您的配件申请已被退回");
			templateDataMap.put("keyword1", "退回");
			templateDataMap.put("keyword2", "配件信息专员");
			templateDataMap.put("keyword3", DateUtil.now());
			templateDataMap.put("remark", "请前往梯无忧维保小程序【我的申请】重新提交处理");
			templateDataMap.put("params", skipUrl);
			asyncUtils.sendWeiXinTemplate(applyUserInfo.getOpenid(), TemplateMsgConstant.T_APPROVE_RESULT_ID, templateDataMap);
			log.info("===========发送审批结果模板消息,申请人:[{}]===========", applyUserInfo.getUserName());
		}
	}
}
